//
//  MultiFileDownloader.swift
//  MultiFileDownloader
//
//  Created by Fanxx on 2021/10/25.
//  Copyright © 2021 JunYue. All rights reserved.
//

import Foundation

open class M3u8Downloader: MultiFileDownloader {
    public let m3u8Url: String
    private let m3u8Parser: M3u8Parser
    /// m3u8链接及目录名
    public init(url: String, downloadPath: URL, directoryName: String) {
        self.m3u8Url = url
        let directoryPath = downloadPath.appendingPathComponent(directoryName)
        self.m3u8Parser = M3u8Parser(identifier: directoryName, downloadPath: directoryPath)
        super.init(downloadList: [], downloadPath: directoryPath)
    }
  
    /// 开始下载
    open override func unsafeStart() {
        self.createDownloadDirectoryIfNotExist()
        self.m3u8Parser.downloadM3u8File(self.m3u8Url) { [weak self] result in
            guard let self = self else { return }
            switch result {
            case let .success(tsList):
                self.downloadList = tsList
                self.superStart()
            case let .failure(error):
                self.onFailed(error)
            }
        }
    }
    private func superStart() {
        super.unsafeStart()
    }
}
